<template>
  <view class="container">	

	<view class="question-item">
	  <view class="desc">
		以下部分问题已根据您的现有信息填写，如与事实不符请自行修改。
	  </view> 
	</view>
 
    <!-- 内容区域 -->
    <view class="content">
      <view class="question-list">
        <view class="question-item" v-for="(question, qIndex) in questionaire.questionaireQuestionList" :key="question.id">
          <view class="question-title">{{ qIndex + 1 }}. {{ question.content }}</view>
          <view class="options">
            <view class="option" v-for="(option, oIndex) in question.questionaireSelectVoList" :key="option.id"
              :class="{ selected: userAnswers[question.id] === option.id }"
              @click="selectOption(question.id, option.id)">
              <view class="radio">
                <view class="inner" v-if="userAnswers[question.id] === option.id"></view>
              </view>
              <text class="option-text">{{ option.content }}</text>
            </view>
          </view>
        </view>
      </view>

      <view class="submit-button" @click="submitForm">
        <text>提交</text>
      </view>
    </view>

  </view>
</template>


<script>
import { getQuestionaireAllDetail,getStrokeUserInfo,getUserIndicatorInfo,submitAnswers } from '@/common/api.js'

export default {
  data() {
    return {
      questionaire: {}, // 问卷数据
      questionaireId: '',
      userAnswers: {}, // 每道题的选择 { questionId: selectId }
      userInfo: {},
	  userIndicator: {}
	}
  },
  onLoad(options) {
    this.questionaireId = options.id
    this.loadQuestionaireAllDetail()
	this.loadUserInfo()
	this.loadUserIndicator()
  },
  methods: {
    async loadQuestionaireAllDetail() {
      try {
        const res = await getQuestionaireAllDetail(this.questionaireId)
        this.questionaire = res.data
		// 如果 userInfo 已加载,初始化选项
		if (Object.keys(this.userInfo).length) {
		  this.autoFillAnswersFromUserInfo()
		}
      } catch (e) {
        console.error('加载问卷失败', e)
      }
    },
	async loadUserInfo() {
	  try {
	    const userRes = await getStrokeUserInfo()
	    this.userInfo = userRes.data
	  } catch (e) {
	    console.error('加载用户信息失败', e)
	  }
	},
	async loadUserIndicator() {
	  try {
	    const userIndicatorRes = await getUserIndicatorInfo()
	    this.userIndicator = userIndicatorRes.data
		console.log('健康指标', userIndicatorRes)
	  } catch (e) {
	    console.error('加载用户健康指标失败', e)
	  }
	},
	autoFillAnswersFromUserInfo() {
	    this.questionaire.questionaireQuestionList.forEach(question => {
	      const qContent = question.content
	
	      if (qContent.includes('年龄')) {
			const currentYear = new Date().getFullYear()
	        const age = currentYear - this.userInfo.age
	        const matched = question.questionaireSelectVoList.find(opt => {
	          if (age < 65 && opt.content.includes('<65')) return true
	          if (age >= 65 && age <= 75 && opt.content.includes('65~75')) return true
	          if (age > 75 && opt.content.includes('>75')) return true
	        })
	        if (matched) {
	          this.$set(this.userAnswers, question.id, matched.id)
	        }
	      }
	
	      if (qContent.includes('高血压')) {
			const value = this.userInfo.otherDisease.includes('高血压') ? 1 : 0;
	        const matched = question.questionaireSelectVoList.find(opt =>
	          (value && opt.content === '是') || (!value && opt.content === '否')
	        )
	        if (matched) {
	          this.$set(this.userAnswers, question.id, matched.id)
	        }
	      }
	
	      if (qContent.includes('糖尿病')) {
	        const value = this.userInfo.otherDisease.includes('糖尿病') ? 1 : 0;
	        const matched = question.questionaireSelectVoList.find(opt =>
	          (value && opt.content === '是') || (!value && opt.content === '否')
	        )
	        if (matched) {
	          this.$set(this.userAnswers, question.id, matched.id)
	        }
	      }
	
	      if (qContent.includes('TIA')) {
	        const value = this.userInfo.strokeDiseaseHistory.includes('TIA' || '脑梗死') ? 1 : 0;
	        const matched = question.questionaireSelectVoList.find(opt =>
	          (value && opt.content === '是') || (!value && opt.content === '否')
	        )
	        if (matched) {
	          this.$set(this.userAnswers, question.id, matched.id)
	        }
	      }
		  
		  if (this.userIndicator && qContent.includes('吸烟')) {
			const value = this.userIndicator.smoke > 0 ? 1 : 0;
			const matched = question.questionaireSelectVoList.find(opt =>
			     (value && opt.content === '是') || (!value && opt.content === '否')
			  )
			if (matched) {
				this.$set(this.userAnswers, question.id, matched.id)
			  }
			}

		  
	    })
	  },
    goBack() {
      uni.navigateBack()
    },
    selectOption(questionId, selectId) {
      this.$set(this.userAnswers, questionId, selectId)
    },
	async submitForm() {
		const allQuestions = this.questionaire.questionaireQuestionList || [];
		
		// 1. 校验是否每题都有答案
		const unanswered = allQuestions.filter(q => !(q.id in this.userAnswers));
		if (unanswered.length > 0) {
			uni.showToast({
				title: '请完成所有题目再提交',
				icon: 'none'
			});
			return;
		}
		
		// 2. 构造提交数据
		const data = Object.entries(this.userAnswers).map(([questionId, selectId]) => ({
			questionId,
			selectId
		}));
		
		// 3. 发起提交请求
		try {
			const res = await submitAnswers(data);
			uni.showToast({
				title: '提交成功',
				icon: 'success'
			});
			// 提交成功后延时返回上一个页面
			setTimeout(() => {
				uni.navigateBack();
			}, 1500);
		} catch (error) {
			uni.showToast({
				title: error.message || '网络错误',
				icon: 'none'
			});
		}
	}
  }
}
</script>

<style lang="scss" scoped>
	.container {
		background-color: #f5f5f5;
		min-height: 100vh;
		display: flex;
		flex-direction: column;
	}
	
	.nav-bar {
		display: flex;
		align-items: center;
		padding: 20rpx 30rpx;
		background-color: #fff;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		
		.left {
			width: 60rpx;
		}
		
		.title {
			flex: 1;
			text-align: center;
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
			margin-right: 32rpx;
		}
		
		.right {
			width: 60rpx;
		}
	}
	
	
	
	.description-card {
		background-color: #fff;
		padding: 16px;
		border-radius: 8px;
		margin-bottom: 16px;
		
		.title {
			font-size: 18px;
			font-weight: bold;
			color: #333;
			margin-bottom: 8px;
		}
		
		.desc {
			font-size: 14px;
			color: #666;
			line-height: 1.4;
		}
	}

	.question-item {
	  background-color: #fff;
	  padding: 16px;
	  border-radius: 8px;
	  margin: 12px 16px;
	
	  .question-title {
	    font-size: 16px;
	    font-weight: 500;
	    color: #333;
	    margin-bottom: 12px;
	  }
	
	  .options {
	    display: flex;
	    flex-direction: column;
	    gap: 12px;
	  }
	
	  .option {
	    display: flex;
	    align-items: center;
	    padding: 12px;
	    border-radius: 8px;
	    border: 1px solid #ddd;
	    background-color: #fff;
	    transition: all 0.3s;
	
	    &.selected {
	      border-color: #2979ff;
	      background-color: #e8f2ff;
	    }
	
	    .radio {
	      width: 20px;
	      height: 20px;
	      border-radius: 50%;
	      border: 1px solid #ccc;
	      display: flex;
	      align-items: center;
	      justify-content: center;
	      margin-right: 12px;
	
	      .inner {
	        width: 12px;
	        height: 12px;
	        border-radius: 50%;
	        background-color: #2979ff;
	      }
	    }
	
	    .option-text {
	      font-size: 14px;
	      color: #333;
	    }
	  }
	}


	
	.submit-button {
		background-color: #2979ff;
		height: 44px;
		border-radius: 22px;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 20px 0;
		
		text {
			color: #fff;
			font-size: 16px;
			font-weight: 500;
		}
		
		&.disabled {
			background-color: #a0cfff;
		}
	}
</style> 